﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data.Common;

namespace WorkNodeFramework
{
    public class ParameterIndexCollection:IEnumerable<ParameterIndex>
    {
        Dictionary<string, int> parCount = new Dictionary<string, int>();
        List<ParameterIndex> pars = new List<ParameterIndex>();

        public ParameterIndex SetParameterIndex(string baseName, object value) { 
            int count = 0;
            if (!parCount.ContainsKey(baseName))
                parCount[baseName] = 0;
            else
            {
                count = parCount[baseName];
                count++;
                parCount[baseName] = count;
            }
            ParameterIndex p = new ParameterIndex(baseName, value, count);
            pars.Add(p);
            return p;
        }

        #region IEnumerable<ParameterCount> Members

        public IEnumerator<ParameterIndex> GetEnumerator()
        {
            return pars.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return ((IEnumerable)pars).GetEnumerator();
        }

        #endregion

        public DbParameter[] ToDbParameters(DataProvider provider)
        {
            if (pars.Count == 0)
                return new DbParameter[0];
            List<DbParameter> dbParams = new List<DbParameter>();
            foreach (ParameterIndex pi in pars)
            {
                string baseName = pi.BaseName + pi.Index.ToString();
                string parName = provider.GetParameterName(baseName);
                object val = pi.Value;
                DbParameter p = provider.CreateParameter(parName, pi.Value);
                dbParams.Add(p);
            }
            return dbParams.ToArray();
        }
    }
}
